package org.fall.mvc.handler;

import crowd.entity.Auth;
import crowd.entity.Role;
import org.fall.service.api.AdminService;
import org.fall.service.api.AuthService;
import org.fall.service.api.RoleService;
import org.fall.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author XZ
 * @create 2021-12-19 14:28
 */
@Controller
public class AssignHandler {
    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @ResponseBody
    @RequestMapping("/assign/do/save/role/auth/relationship.json")
    public ResultEntity<String> saveRoleAuthRelationship(@RequestBody Map<String, List<Integer>> map) {
        authService.saveRoleAuthRelationship(map);
        System.out.println(map);
        return ResultEntity.successWithoutData();
    }

    // 获得被勾选的auth信息
    @ResponseBody
    @RequestMapping("/assign/get/checked/auth/id.json")
    public ResultEntity<List<Integer>> getAuthByRoleId(Integer roleId){
        List<Integer> authIdList = authService.getAuthByRoleId(roleId);
        return ResultEntity.successWithData(authIdList);
    }

    @ResponseBody
    @RequestMapping("/assign/get/tree.json")
    public ResultEntity<List<Auth>> getAllAuth() {
        List<Auth> authList = authService.getAll();
        return ResultEntity.successWithData(authList);
    }

    @RequestMapping("assign/do/assign.html")
    public String addAssignedRoleList(@RequestParam(value = "roleIdList",required = false) List<Integer> roleIdList,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "keyword", defaultValue = "") String keyword,
                                      @RequestParam(value = "adminId") Integer adminId) {
        adminService.saveAdminRoleRelationship(adminId, roleIdList);
        return "redirect:/admin/page/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
    }


    @RequestMapping("assign/to/page.html")
    public String toAssignRolePage(@RequestParam(value = "adminId") Integer adminId, ModelMap modelMap) {
        List<Role> UnAssignedRoleList = roleService.queryUnAssignedRoleList(adminId);
        List<Role> AssignedRoleList = roleService.queryAssignedRoleList(adminId);
        modelMap.addAttribute("UnAssignedRoleList", UnAssignedRoleList);
        modelMap.addAttribute("AssignedRoleList", AssignedRoleList);
        return "assign-role";
    }
}
